<template>
    <div class="order">
		<!-- 公共标题 -->
		<div class="common-tel">
			收货人信息
			<div class="common-tel-dot">
				<em></em>
				<em></em>
				<em></em>
			</div>
		</div>
		<!-- 收货人信息 -->

		<div class="common-form" v-if=" add != '' ">
			<div class="order-info">
				<a  class="order-info-a" @click="switchTo('/AddressList')"></a>
				<div class="order-info-name">
					{{add.name}}  {{add.tel}}
				</div>
				<div class="order-info-add">
					<label>地址：</label>
					<span>{{add.province}}{{add.city}}{{add.area}}{{add.address}}</span>
				</div>
			</div>
		</div>
		<div class="common-form" v-else>
			<router-link :to="'/AddressAdd'" >
				<div class="order-info-none"><em>+</em>添加收货地址</div>
			</router-link> 
		</div>
		<!-- 公共标题 -->
		<div class="common-tel">
			商品信息
			<div class="common-tel-dot">
				<em></em>
				<em></em>
				<em></em>
			</div>
		</div>
		<!-- 商品信息 -->
		<div class="common-form" v-for="g in goods">
			<div class="order-shop">
				<p class="order-shop-tel"><i></i>{{g.merchant_name}}</p>
				<div class="order-shop-info" v-for="(item, index) in g.goodsList" :key="index">
					<img :src="url + item.data.thumbnail">
					<div>
						<p>{{item.data.goods_title}}</p>
						<p>{{item.data.spec_2}} {{item.data.spec_1}} {{item.data.quantity}}件</p>
						<p>
							<a v-if="vip == 0">￥{{item.data.market_price}}</a>
							<a v-else>￥{{item.data.vip_price}}</a>
						</p>
					</div>
				</div>
				<!-- <div class="order-shop-more">购买数量 <em>{{g.quantity}}</em></div> -->
				<div class="order-shop-more">运费 <em>{{g.freight}}</em></div>
				<div class="order-shop-more">商品金额 
					<a v-if="vip == 0" class="order-shop-more-p">￥{{g.market_price}}</a>
					<a class="order-shop-more-p" v-else>￥{{g.vip_price}}</a>
				</div>
				<div class="order-shop-more">买家留言 <input type="text" placeholder="选填" class="order-shop-more-ipt"/></div>
			</div>
		</div>
		<!-- 公共标题 -->
		<!-- <div class="common-tel">
			支付方式
			<div class="common-tel-dot">
				<em></em>
				<em></em>
				<em></em>
			</div>
		</div> -->
		<!-- 支付方式 -->
		<!-- <div class="common-form">
			<div class="order-pay">
				<img src="build/img/1.jpg" alt="" />
				<div>
					<p>微信支付</p>
					<p>微信支付  更快更安全</p>
				</div>
				<em></em>
			</div>
			<div class="order-pay">
				<img src="build/img/2.jpg" alt="" />
				<div>
					<p>微信支付</p>
					<p>微信支付  更快更安全</p>
				</div>
				<em class="order-pay-pink"></em>
			</div>
		</div> -->
		<div class="footer-100"></div>
		<!-- 支付 -->
		<div class="order-footer">
			<div>
				实付款：<span>￥<em>{{total}}</em></span>
			</div>
			<a @click="pay">立即支付</a>
		</div>
	</div>
</template>

<script>
import axios from "axios";
import qs from 'qs'
import url from 'url'
import wx from 'weixin-jsapi'
    export default {
		name:'',
		data () {
            return {
				add:{},
				firm:[],
				firms:[],
				url:'http://api.huiwanzhong365.com',
				detail:[],
				total_price:0,
				price:0,
                vip:'',
				cart:[],
				num:[],
				total:'',
				goods:[],
				province:'',
				marketPrice:0,
				firm3:''
				// {
				// 		merchant_id:'',
				// 		merchant_name:'',
				// 		goodsList:[]
				// 	}
            }
        },
        mounted(){
            
			this.cart = JSON.parse(sessionStorage.getItem('cart') || '[]')
			
			this.getAdd();
			this.confirm();
			//this.yunfei();
			for(let index = 0; index < this.cart.length; index++){
				this.total_price = this.total_price  + Number(this.cart[index].price)
			}
			for (let index = 0; index < this.cart.length; index++) {
				this.firm3 = {
						goods_id:this.cart[index].goods_id,
						attr_id:this.cart[index].attr_id,
						quantity:this.cart[index].quantity,
					}
			}
			this.firms.push(this.firm3)
		},
		methods:{
			switchTo(path){
				// console.log(this.$router)
				this.$router.push(path)
			},    
			//获取收货地址
			getAdd:function(){
				var that = this
				var openid =localStorage.getItem("openid")
				//console.log(openid)
                var upload = {
                    openid:openid,
                }
                this.$http.post('/vipmember/index/getDefaultAddress',qs.stringify(upload)).then(rs=>{
					//console.log(rs.data)
					this.add = rs.data
					this.province = rs.data.province
					// this.yunfei(rs.data.province) 
                }).catch(err=>{
                    console.log(err)
                })
			}, 
			//查看运费
			yunfei:function(goodsId, callback){
				var that = this
				// for(let index = 0; index < this.cart.length; index++){
				// 	this.num.push(this.cart[index].goods_id)
				// 	console.log(this.num)
				// 	//this.total_price = this.total_price  + Number(this.cart[index].price)
				// }
				//console.log(this.total_price)
				var openid = localStorage.getItem("openid")
				console.log(goodsId.join(","))
                var upload = {
					openid:openid,
					province:this.province,
					// goods_id:this.num.join(",")
					goods_id:goodsId.join(",")
                }
                this.$http.post('/index/merchant/goods/query_freight',qs.stringify(upload)).then(rs=>{
					console.log(rs.data)
					that.price = rs.data.price
					callback && callback(rs.data.price)
					//this.add = rs.data
					
					this.total = Number(this.total_price) + Number(that.marketPrice)
					console.log(this.total_price , that.marketPrice)
					
                }).catch(err=>{
                    console.log(err)
                })
			},
			// 确认订单信息
			confirm:function(){
				//console.log(this.$route.params.id)
				var that = this
				var openid = localStorage.getItem("openid")
                for (let index = 0; index < this.cart.length; index++) {
                    var firm2 = {
						goods_id:this.cart[index].goods_id,
						attr_id:this.cart[index].attr_id,
						quantity:this.cart[index].quantity,
					}
				    this.firm.push(firm2)
                }
				//console.log(JSON.stringify(this.firm))
                var upload = {
					openid:openid,
					list:JSON.stringify(this.firm),
                }
                this.$http.post('/index/merchant/goods/affirmOrder',qs.stringify(upload)).then(rs=>{
					console.group('o')
					// var rs = {
					// 	data: {
					// 		list: [{"data":{"id":37,"goods_title":"会员商城测试商品100","thumbnail":"\/uploads\/20190131\/1eb24ded8ecbc177.jpg","price":"0.01","merchant_id":2,"merchant_name":"鱼酷烤鱼2","vip_price":0.02,"quantity":2}},{"data":{"id":38,"goods_title":"会员商城测试商品101","thumbnail":"\/uploads\/20190131\/1eb24ded8ecbc177.jpg","price":"0.01","merchant_id":1,"merchant_name":"鱼酷烤鱼大悦城店","vip_price":0.03,"quantity":3}},{"data":{"id":40,"goods_title":"123","thumbnail":"\/uploads\/20190131\/b218cc70d58129347e9ffeb4bf1dde33.jpg","price":"4.00","merchant_id":1,"merchant_name":"鱼酷烤鱼大悦城店","vip_price":4,"quantity":1}}]
					// 	}
					// }
					// console.log(rs.data.list)
					that.goods.length = 0
					var data = rs.data.list,
						goods = {}
					
					console.log('[1]',data,goods)
					if(data.length > 0) {
						data.forEach(el => {
							console.log('[2]',el)
							if (goods[el.data.merchant_id] == undefined) {
								goods[el.data.merchant_id] = {
									merchant_id: el.data.merchant_id,
									merchant_name: el.data.merchant_name,
									quantity: 0,
									market_price: 0,
									vip_price: 0,
									freight:0,
									goods_id:[],
									goodsList: []
								}
							}
							goods[el.data.merchant_id].goodsList.push(el)
							goods[el.data.merchant_id].goods_id.push(el.data.id)
							goods[el.data.merchant_id].quantity += el.data.quantity
							goods[el.data.merchant_id].market_price += el.data.market_price
							goods[el.data.merchant_id].vip_price += el.data.vip_price
							goods[el.data.merchant_id].freight = this.price
						});
						console.log('[3]',goods, that.goods)
						
						for (let i in goods) {
							this.yunfei(goods[i].goods_id, function(freight) {
								goods[i].freight = freight
								that.goods.push(goods[i])
								// that.goods[j - 1].freight = freight
								console.log('[5]', goods, freight, i)

								that.marketPrice += Number(freight)
								console.log(that.marketPrice)
							})
						}
						// that.marketPrice += freight
						
				
						console.log('[4]', that.goods)
					}
					console.groupEnd()
					//this.add = rs.data
					this.detail = rs.data.list
					//console.log(this.detail)
					// this.total_price = rs.data.total_price
					this.vip = rs.data.vip
                }).catch(err=>{
                    console.log(err)
                })
			},
			pay:function(){
                var openid = localStorage.getItem("openid")
                
				
				console.log(this.firms)
				var data = {
					goods:this.firms,
					address:[
						{
							addressee:this.add.name,
							number:this.add.tel,
							province:this.add.province,
							city:this.add.city,
							area:this.add.area,
							address:this.add.address
						}
					]
				}
				//console.log(JSON.stringify(data))
				var upload = { 
					openid:localStorage.getItem("openid"),
					list: JSON.stringify(data)
                }
                this.$http.post('/index/merchant/goods/memberOrder',qs.stringify(upload)).then(res=>{
					console.log(res.data)
					// if(res.data.status = 400){
					// 	layer.msg(res.data.info);
					// }else{
						layer.msg(res.data.info);
						wx.chooseWXPay({
							// appId:res.data.appId,
							timestamp:res.data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
							nonceStr: res.data.nonceStr, // 支付签名随机串，不长于 32 位
							package:res.data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
							signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
							paySign: res.data.paySign, // 支付签名
							success: function (res) {
								// 支付成功后的回调函数
								console.log('pay success');
								this.$router.push({name:'vipOrderList'});
							},
							error: function (res) {
								// 支付失败的回调函数
								console.log(res);
								//alert(res.errMsg);
							}
						});
					// }
					
                }).catch(err=>{
					console.log(err)
                })
			},
		},
		
    }
</script>

<style scoped>
.order-shop-more-p{
	float:right;
}
.order-shop-more-ipt{
    width: 130px;
    text-align: right;
    border: 0;
    outline: none;
	float: right;
    padding: 10px 0;	
}
</style>